<template>
  <div>
    <Breadcrmb title1="首页" title2="权限管理" title3="角色列表"></Breadcrmb>

        <el-card style="margin-top:20px">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

             <el-table :data="tableData" style="width: 100%">
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-row class="vcenter" :class="index==0?'':'bdtop'" :gutter="20" v-for="(item,index) in scope.row.children" :key="item.id">
                      <el-col :span="5">
                        <!-- {{item.authName}}  level1 -->
                        <el-tag>{{item.authName}}</el-tag>
                      </el-col>
                      <el-col :span="19">
                         <el-row  class="vcenter bdtop" v-for="item2 in item.children" :key="item2.id">
                            <el-col :span="6">
                              <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                              <!-- <i class="el-icon-caret-right"></i> -->
                            </el-col>
                            <el-col :span="18">
                              <el-tag closable type="warning" @close="removeRightById(scope.row,item3.id)"  v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                            </el-col>
                         </el-row>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称">
                </el-table-column>
                <el-table-column prop="roleDesc" label="角色描述">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="toView(scope.row)"></el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click='del(scope.row)'></el-button>
                  <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false"><el-button size="mini" type="warning" icon="el-icon-setting" @click='showDialog(scope.row)'></el-button></el-tooltip>
                </template>
                </el-table-column>
             </el-table>
          <el-dialog title="分配权限" :visible.sync="setRightsVisidle" width="50%" @close="setRightClosed">
           
           <!--  -->
               <el-tree
              :data="rightList"
              ref="treeRef"
              show-checkbox
              node-key="id"
              default-expand-all
              :default-checked-keys="defKeys"
              :props="treeProps"
              >
            </el-tree>
            <span slot="footer" class="dialog-footer">
                    <el-button @click="setRightsVisidle=false">取 消</el-button>
                    <el-button type="primary" @click="allRights">确 定</el-button>
                </span>
          </el-dialog>

          <el-dialog title="添加角色" :before-close="handleClose" :visible.sync="dialogVisible" width="40%">
                <el-form :rules="rules" ref="addForm" label-width="80px" :model="userForm">

                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="userForm.roleName"></el-input>
                    </el-form-item>

                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="userForm.roleDesc"></el-input>
                    </el-form-item>

                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>

            <el-dialog title="添加角色" :before-close="handleClose" :visible.sync="dialogVisible2" width="40%">
                <el-form :rules="rules" ref="addForm" label-width="80px" :model="userForm">

                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="userForm.roleName"></el-input>
                    </el-form-item>

                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="userForm.roleDesc"></el-input>
                    </el-form-item>

                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="xgUser">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
  </div>
</template>

<script>
import {getRolesList,DelRolesList,getAddUser,getDeleteUser,getxgUser} from '@/api/roles.js'
export default { 
  created(){
    this.getUser();
  },
  methods:{
    //修改
        toView(data){
            console.log(data);
            this.userForm.id = data.id;
            this.userForm.roleDesc = data.roleDesc;
            this.userForm.roleName = data.roleName;
            this.dialogVisible2=true;
        },
        async xgUser(){
            var {data:res}=await getxgUser(`roles/${this.userForm.id}`,this.userForm);
            console.log(res);
            if(res.meta.status !==200){
                return this.$message.error("修改失败！")
            }
            this.$message.success("修改成功");
            this.getUser();
            this.handleClose();
        },
    async del(row){
        var {data:res}=await getDeleteUser(`roles/${row.id}`);
        console.log(res);
        if(res.meta.status !==200){
            return this.$message.error("删除失败！")
        }
        this.$message.success("删除成功");
        this.getUser();
    },

    async addUser(){
      var {data:res}=await getAddUser(this.userForm);
            console.log(res);
            if(res.meta.status !==201){
                return this.$message.error("添加失败！")
            }
            this.$message.success("更新用户添加成功");
            this.handleClose();
            this.getUser();
    },

    async allRights(){
    console.log(this.$refs.treeRef.getCheckedKeys());
    console.log(this.$refs.treeRef.getHalfCheckedKeys());

      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr=keys.join(",");
      // alert(this.roleId);
      const {data:res} =await this.request.post(`roles/${this.roleId}/rights`,{rids:idStr});
  console.log(res);
      if(res.meta.status !==200){
         return this.$message.error("获取权限失败！")
      }
      this.$message.success("分配权限成功");
      this.setRightsVisidle=false;
      this.getUser();
    },
    //关闭对话框
    setRightClosed(){
      this.defKeys=[];
    },
    getLeafkeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item)=>this.getLeafkeys(item,arr))
    },
    async showDialog(role){
      this.roleId=role.id;

      var {data:res}=await this.request.get("rights/tree");
        console.log(res);
        if(res.meta.status !==200){
            return this.$message.error("获取权限列表获取失败！")
        }
        this.rightList=res.data;

        this.getLeafkeys(role,this.defKeys)

        // for (var i = 0; i < role.children.length; i++) {
        //   var item=role.children[i];
        //   // console.log(item.authName);
        //   for (var j = 0; j < item.children.length; j++) {
        //     var item2=item.children[j];
        //     // console.log("\t"+item2.authName);
        //     for (var k = 0; k < item2.children.length; k++) {
        //       var item3=item2.children[k];
        //       // console.log("\t\t"+item3.authName);
        //       this.defKeys.push(item3.id)
        //     }
        //   }
        // }

        this.setRightsVisidle=true;

    },
    async getUser(){
         var {data:res}=await getRolesList();
        console.log(res);
        if(res.meta.status !==200){
            return this.$message.error("获取失败！")
        }
        this.tableData=res.data;
    },
     async removeRightById(role,id){

         const condel=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        if(condel==='confirm'){
          var data={
            roleId:role.id,
            rightId:id
          }
          var {data:res} =await DelRolesList(data)
            console.log(res);
            role.children=res.data
            if(res.meta.status ===200){
              this.$message({
              type: 'success',
              message: res.meta.msg
            });
          }
        }
        
        
        // .then(async() => {
        //   var data={
        //     roleId:roleId,
        //     rightId:id
        //   }
        //   var {data:res} =await DelRolesList(data)
        //   console.log(res);
        //   this.$message({
        //     type: 'success',
        //     message: '删除成功!'
        //   });
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消删除'
        //   });          
        // });
    },

    handleClose() {
            // this.$refs['rulesForm'].resetFields();
            this.userForm.email = '';
            this.userForm.username = '';
            this.userForm.mobile = '';
            this.userForm.password = '';
            this.dialogVisible = false;
            this.dialogVisible2 = false;
        },
  },
  data(){
    return{
      tableData:[],
      rightList:[],
      defKeys:[],
      setRightsVisidle:false,
      dialogVisible2:false,
      treeProps:{
       children: 'children',
          label: 'authName'
      },
      roleId:'',
      dialogVisible:false,
      userForm:{
          roleName:'',
          roleDesc:''
      },
      rules: {
                username: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }],
                password: [{
                    required: true,
                    message: '请输入角色描述',
                    trigger: 'blur'
                }],
      }
    }
  }
}
</script>

<style>
  .el-tag{
      margin: 7px;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
</style>